﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MS.Utility.Common
{
    public class PageHelper
    {
        /// <summary>
        /// 请求页
        /// </summary>
        public int Page { get; set; }
        /// <summary>
        /// 页大小
        /// </summary>
        public int PageSize { get; set; }
        /// <summary>
        /// 是否倒序
        /// </summary>
        public bool OrderDesc { get; set; }

        public PageHelper() { }
        /// <summary>
        /// 分页转换（根据偏移量、页大小及排序字符串转换为请求页、页大小及是否倒序）
        /// </summary>
        /// <param name="offset">页偏移量</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="orderBy">排序字符串（asc或desc）</param>
        public PageHelper(int offset, int pageSize, string orderBy = null)
        {
            this.PageSize = pageSize;
            this.Page = offset / pageSize + 1;
            if (orderBy == null)
                this.OrderDesc = true;
            else
                this.OrderDesc = string.IsNullOrEmpty(orderBy.Trim()) ? true : orderBy.ToLower() != "asc";
        }

        public static int StartRowIndex(int rows, int page)
        {
            return page <= 0 ? 0 : rows * (page - 1);
        }

        /// <summary>
        /// 根据页大小及总记录数计算总页数
        /// </summary>
        /// <param name="pageSize">页大小</param>
        /// <param name="totalCount">总记录数</param>
        /// <returns>总页数</returns>
        public static int PageCount(int pageSize, int totalCount)
        {
            return pageSize == 0 ? 0 : (totalCount - 1) / pageSize + 1;
        }
    }
}
